import time
from django.core.cache import cache
import jwt
import typing as t

EXPIRE_TIME = 500 * 60 * 1000
KEY = "CxqGrrIsXA82CF1b"
TIME_OUT = 30 * 60  # 30min


def encrypt(payload: dict, username: t.Optional[str] = None) -> str:
    """加密"""
    encoded = jwt.encode(payload, username + KEY, algorithm="HS256")
    return encoded


def decrypt(encoded: str, username: t.Optional[str] = None) -> str:
    """解密"""
    decoded = jwt.decode(encoded, username + KEY, algorithms="HS256")
    return decoded


def create_token(username):
    """生成token信息"""
    # "iat": time.time()
    payload = {"aud": username, "exp": int(time.time()) + EXPIRE_TIME}
    token = encrypt(payload, username)
    # 放入缓存
    cache.set(username, token, TIME_OUT)
    return token


# 获取payload
def get_payload(token):
    payload = jwt.decode(token, '', algorithm=['HS256'], verify=False)
    return payload


# 通过token获取用户名
def get_username(token):
    payload = jwt.decode(token, '', algorithm=['HS256'], verify=False)
    return payload['aud']


# 验证户名
def check_token(token):
    username = get_username(token)
    last_token = cache.get(username)
    if last_token:
        return last_token == token
    return False


# 认证
def check_user_token(token, username):
    last_token = cache.get(username)
    if last_token:
        return last_token == token
    return False
